package com.sw.c.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * http请求工具方法
 */
public class HttpClientUtils {


    public static final String CHARSET = "UTF-8";

    /**
     * GET请求
     * @param url   地址
     * @param param 参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.setParameter(key, param.get(key).toString());
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            //@Mfh 20220221 (获取结束立马将流关闭了，但是传输还没有结束了呢，所以就出现了上面的异常信息|设置http传输协议版本，改为1.0，这样消息体就会一次性全部传过来) 解决org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected错误
            httpGet.setProtocolVersion(HttpVersion.HTTP_1_0);//
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
//                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     * 通用httpclient调用接口
     * @param url 请求路径
     * @return
     */
    public static String doPost(String url, String params){
        String result = null;
        // 创建http连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        CloseableHttpResponse response = null;
        try {
            if (null != params){
                httpPost.setEntity(new StringEntity(params,"UTF-8"));
            }
            response = httpClient.execute(httpPost);

            if(response != null && response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * POST 请求
     *
     * @param url   地址
     * @param param 参数
     * @return
     */
    public static String doPost(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
                }
                // 创建表单的Entity类
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, CHARSET);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     * 适用于post请求并传送form-data数据（同样适用于post的Raw类型的application-json格式）
     * @param url
     * @param params
     * @return
     */
    public static String doPostFormData(String url, Map<String, Object> params) {
        String result = null;
        // 创建http连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
            }
            post.setEntity(new UrlEncodedFormEntity(nvps, CHARSET));
            response = httpClient.execute(post);
            if(response != null && response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity,CHARSET);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送POST表达请求
     * @param url
     * @param params
     */
    public static String doPostFormData2(String url, Map<String, Object> params) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        MultipartEntityBuilder  builder = MultipartEntityBuilder.create();
        builder.addTextBody("flag", params.get("flag").toString());
        builder.addTextBody("account", params.get("account").toString());
        builder.addTextBody("accessToken", params.get("accessToken").toString());
        builder.addTextBody("json", params.get("json").toString());
        CloseableHttpResponse resp = null;
        try {
            httpPost.setEntity(builder.build());
            resp = client.execute(httpPost);
            //注意，返回的结果的状态码是302，非200
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = resp.getEntity();
                respContent = EntityUtils.toString(entity, CHARSET);
            }
            return respContent;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                client.close();
                if(resp != null) {
                    resp.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return respContent;
    }



    public static HttpResponse sendHttpPostRequest(String url, String token,String body) throws IOException {

        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 第三方接口url
        HttpPost httpPost = new HttpPost(url);
        // 设置请求的Header
        httpPost.setHeader("Content-Type", "application/json");
        // 添加Token到请求头
        httpPost.setHeader("Authorization", token);
        // 设置请求的参数
        String jsonParams = body;
        StringEntity entity = new StringEntity(jsonParams, "UTF-8");
        httpPost.setEntity(entity);
        // 执行请求并返回响应
        return httpClient.execute(httpPost);
    }


}
